package com.example.flowabledemo.controller;

import com.example.flowabledemo.data.vo.HistoryProcessVo;
import com.example.flowabledemo.service.FlowableService;
import io.swagger.annotations.ApiOperation;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.flowable.engine.HistoryService;
import org.flowable.engine.RepositoryService;
import org.flowable.engine.RuntimeService;
import org.flowable.engine.TaskService;
import org.flowable.engine.history.HistoricActivityInstance;
import org.flowable.engine.runtime.ProcessInstance;
import org.flowable.task.api.Task;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author linke
 * @date 2020/11/25 21:49
 * @description
 */
@Controller
public class FlowableController {

  @Autowired
  private HttpServletRequest request;
  @Autowired
  private FlowableService flowableService;


  @ApiOperation(value = "查看具体流程", notes = "根据流程实例id")
  @PreAuthorize("authenticated")//需要登录后才能访问
  @GetMapping("processDetail/{processId}")
  public String processDetail(@PathVariable("processId") String processId) {
    request.setAttribute("processId", processId);
    List<HistoryProcessVo> vos = flowableService.getHistory(processId);
    request.setAttribute("his", vos);
    request.setAttribute("limit", vos.size());
    return "process/process_detail";
  }

  @PreAuthorize("authenticated")//需要登录后才能访问
  @ApiOperation(value = "获取流程图", notes = "根据流程实例id")
  @GetMapping("image/{processId}")
  @ResponseBody
  public void image(@PathVariable("processId") String processId, HttpServletResponse response) {
    try {
      flowableService.createProcessImage(processId, response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }


  @GetMapping(value = {"", "/"})
  public String index() {
    return "index";
  }

  @GetMapping("login")
  public String login() {
    return "user/login";
  }

  @GetMapping("welcome")
  public String welcome() {
    request.setAttribute("now", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
    return "user/welcome";
  }

  @GetMapping("403")
  public String status403() {
    return "status/403";
  }

  @GetMapping("404")
  public String status404() {
    return "status/404";
  }

  @GetMapping("500")
  public String status500() {
    return "status/500";
  }


  @Autowired
  private RuntimeService runtimeService;
  @Autowired
  private TaskService taskService;
  @Autowired
  private RepositoryService repositoryService;
  @Autowired
  private HistoryService historyService;

  //1、启动一个任务   http://localhost:8000/start
  @GetMapping("start")
  @ResponseBody
  public String start() {
    String userId = "zhangsan";
    String money = "江苏南京市级32010000";
    //启动流程
    HashMap<String, Object> map = new HashMap<>();
    map.put("handleUser", userId);//用于后面查询
    map.put("handleGroup", money);
    //startProcessInstanceByKey() 第一个参数是bpmn20.xnl的 <process id="leave_key"/>
    ProcessInstance processInstance = runtimeService.startProcessInstanceByKey("leaveProcesses", map);
    return "提交成功.流程Id为：" + processInstance.getId();
  }

  //2、查询任务组中的任务（经理查询任务列表），获取taskId，供第3部查询    http://localhost:8000/see
  @GetMapping("see")
  @ResponseBody
  public Object see(String id) {
    //userId是开始流程的userId=zhangsan
    List<Task> tasks = taskService.createTaskQuery().taskCandidateGroup("江苏南京市级32010000").list();
    for (Task task : tasks) {
      System.out.println(task.getId());
    }
    if (tasks.isEmpty()) {
      return null;
    }
    return tasks.get(0).getId();
  }

  //3、查询任务 步骤2 查询到的taskId
  @GetMapping("get")
  @ResponseBody
  public Object get(String taskId) {
    //获取第一步 HashMap中的内容
    Map<String, Object> processVariables = taskService.getVariables(taskId);
    //获取任务详情
    Task t = taskService.createTaskQuery().taskId(taskId).singleResult();
    System.out.println(t.toString());
    return processVariables;//返回任务的参数，步骤1 中的 HashMap<String, Object> map = new HashMap<>();
  }

  //4、zhangsan 提交这个请假任务，再调用一次see 查看任务最新 taskid
  @GetMapping("up")
  @ResponseBody
  public Object up(String taskId) {
    //此时已经走到zhangsan处理了，userAction=0 表示撤销流程， 对应测试步骤 1 。userAction=1 表示提交到经理，
    HashMap<String, Object> userAction = new HashMap<>();
    userAction.put("userAction", 1);//提交到经理，=0表示撤销  我们不撤销， zhangsan 直接提交请假到经理处
    taskService.complete(taskId, userAction);
    return "success";
  }

  //5、经理同意，完成流程，此任务id为 步骤4提交后，再调用步骤2获取到的最新taskId
  @GetMapping("com")
  @ResponseBody
  public Object com(String taskId) {
    //此时流程已经走到经理处理了，approval=0 表示不通过，approval=1表示通过
    HashMap<String, Object> userAction = new HashMap<>();
    userAction.put("approval", 1);//直接通过，流程完成
    taskService.complete(taskId, userAction);
    return "success";
  }


  //6、查询历史，步骤1中生成的实例id
  @GetMapping("hi")
  @ResponseBody
  private Object hi(String processId) {
    List<HistoricActivityInstance> activities =
        historyService.createHistoricActivityInstanceQuery()
            .processInstanceId(processId)
            .finished()
            .orderByHistoricActivityInstanceEndTime().asc()
            .list();

    for (HistoricActivityInstance activity : activities) {
      System.out.println(activity.getActivityId() + " took "
          + activity.getDurationInMillis() + " milliseconds");
    }
    return activities;
  }

}
